<?php

namespace App\Http\Controllers;

use App\Models\BusinessModel;
use App\Services\BusinessService;
use App\Services\CategoryService;
use Illuminate\Http\Request;

class BusinessController extends BaseController {

    public function index(Request $request) {
        $this->view_data['category'] = (new CategoryService())->list(["limit"=>999]);
        return view('business.index', $this->view_data);
    }

    public function list(Request $request) {
        $params = $request->all();

        $list = (new BusinessService())->list($params);

        return $this->apiSuccess($list);
    }

    public function create(Request $request) {
        $info_id = $request->get("info_id", 0);
        $info = [];
        if (!empty($info_id)){
            $info = (new BusinessService())->info($info_id);
        }
        $this->view_data['category'] = (new CategoryService())->list(["limit"=>999]);
        $this->view_data['info'] = $info;
        return view('business.add', $this->view_data);
    }

    public function save(Request $request) {
        $data = $request->all();

        $info_id = data_get($data, 'info_id', 0);
        if (empty($info_id)){
            $model = new BusinessModel();
        }else{
            $model = BusinessModel::find($info_id);
        }
        $model->title = data_get($data, 'title', '');
        $model->class_id = data_get($data, 'class_id', '');
        $model->content = data_get($data, 'content', '');
        $model->images = json_decode(data_get($data, 'images'), true);
        $model->save();
        if (!$model->id){
            return $this->apiError('保存失败');
        }
        return $this->apiSuccess('ok');
    }

    public function delete(Request $request) {
        $info_id = $request->get("info_id", 0);

        (new BusinessService())->delete($info_id);
        return $this->apiSuccess('ok');
    }
}